<?php
/**
 * alipay应用网关
 * @author qingyu8@staff.weibo.com
 * @date 2018/03/11
 */
namespace api\modules\v1\controllers;

use common\logic\Order;
use common\logic\Trip;
use yii\web\Controller;
use Yii;
use yii\web\Response;

require_once Yii::$app->vendorPath . '/alipay-sdk-PHP-3.0.1/AopSdk.php';
require_once Yii::$app->vendorPath . '/alipay-sdk-PHP-3.0.1/service/AlipayTradeService.php';
require_once Yii::$app->vendorPath . '/alipay-sdk-PHP-3.0.1/buildermodel/AlipayTradePagePayContentBuilder.php';

class PayController extends Controller {
    public $enableCsrfValidation = false;

    public function actionIndex() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        exit(__METHOD__);
    }

    public function actionPay() {
        if (Yii::$app->user->isGuest) {
            Yii::$app->params['payDebug'] && exit('未登录');
            return $this->redirect('https://cooldive.com.cn');
        }
        $type = Yii::$app->request->post('type', Order::PAY_TYPE_ALI);
        $orderId = Yii::$app->request->post('orderId');
        if (!$orderId && Yii::$app->params['payDebug'] && in_array(Yii::$app->user->id, Yii::$app->params['debug_uids'])) {
            $orderId = $_GET['orderId'];
        }
        if (!$orderId) {
            if (Yii::$app->params['payDebug'] && in_array(Yii::$app->user->id, Yii::$app->params['debug_uids'])){
                var_dump($orderId);
                exit;
            }
            return $this->redirect('https://cooldive.com.cn');
        }
        $res = Order::getDetail(Yii::$app->user->id, $orderId);
        if ($res['err'] != 0) {
            if (Yii::$app->params['payDebug'] && in_array(Yii::$app->user->id, Yii::$app->params['debug_uids'])) exit(__METHOD__ . __LINE__);
            return $this->redirect('https://cooldive.com.cn');
        }
        $order = $res['data'];
        $subject = '趣潜 ' . Trip::getBoatName($order['trip_id']);//max:256
        $body = Yii::$app->request->post('body', '');//max:128
        switch ($type) {
            case Order::PAY_TYPE_ALI:
            case Order::PAY_TYPE_ALI_WAP:
                //构造参数
                $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
                $payRequestBuilder->setBody($body);
                $payRequestBuilder->setSubject($subject);
                $total_amount = Yii::$app->params['payDebug'] && in_array(Yii::$app->user->id, Yii::$app->params['debug_uids']) ? 0.01 : $order['price'] / 100;
                $payRequestBuilder->setTotalAmount($total_amount);//单位：元
                //商户订单号，商户网站订单系统中唯一订单号，必填
                $payRequestBuilder->setOutTradeNo($orderId);

                $config = Yii::$app->params['alipay'];
                $aop = new \AlipayTradeService($config);

                /**
                 * pagePay 电脑网站支付请求
                 * @param $builder 业务参数，使用buildmodel中的对象生成。
                 * @param $return_url 同步跳转地址，公网可以访问
                 * @param $notify_url 异步通知地址，公网可以访问
                 * @return $response 支付宝返回的信息 | 表单（网站支付时）
                 */
                $form='';
                if($type == Order::PAY_TYPE_ALI){
                    $form = $aop->pagePay($payRequestBuilder, $config['return_url'], $config['notify_url']);
                }elseif($type==Order::PAY_TYPE_ALI_WAP){
                    $form = $aop->wapPay($payRequestBuilder, sprintf($config['return_url_wap'], $orderId), $config['notify_url']);
                }
                return $this->render('alipay', [
                    'form' => $form,
                ]);
                break;
            case Order::PAY_TYPE_WECHAT:
            case Order::PAY_TYPE_WECHAT_H5:
                Yii::$app->response->format = Response::FORMAT_JSON;
                require_once Yii::$app->vendorPath . "/WxpayAPI_php_v3.0.1/example/WxPay.JsApiPay.php";
                require_once Yii::$app->vendorPath . "/WxpayAPI_php_v3.0.1/lib/WxPay.Api.php";
                //①、获取用户openid
                $tools = new \JsApiPay();
//                $openId = $tools->GetOpenid();

                $openId = Yii::$app->session->get('wechat_openid');
                //$openId ='o4IzE07WXptEK73Vn6nOLvnO1jAs';
                try{
                    //②、统一下单
                    $input = new \WxPayUnifiedOrder();
                    !$body && $body = '趣潜 - 船宿';
                    $input->SetBody($body);
                    $input->SetAttach("test");
                    $input->SetOut_trade_no($orderId);
                    $total_amount = Yii::$app->params['payDebug'] && in_array(Yii::$app->user->id, Yii::$app->params['debug_uids']) ? 1 : $order['price'];
                    $input->SetTotal_fee($total_amount);//单位为分
                    $input->SetTime_start(date("YmdHis"));
                    $input->SetTime_expire(date("YmdHis", time() + 600));
                    $input->SetGoods_tag("test");
                    $input->SetNotify_url(Yii::$app->params['wechat']['pay.notify_url']);
                    $input->SetTrade_type($type==Order::PAY_TYPE_WECHAT ?"JSAPI":'MWEB');
                    $input->SetOpenid($openId);
                    $unifiedOrderRes = \WxPayApi::unifiedOrder($input);
                    Yii::info($unifiedOrderRes, 'debug' . __METHOD__);
                    if ($type == Order::PAY_TYPE_WECHAT) {
                        $res = json_decode($tools->GetJsApiParameters($unifiedOrderRes),true);
                    }else{
                        $res = $unifiedOrderRes;
                    }

                    //type为PAY_TYPE_WECHAT_H5时，返回参数 mweb_url：支付跳转url
                    return [
                        'code' => 200,
                        'data' => $res,
                    ];
                } catch (\Exception $e) {
                    Yii::error($e, __METHOD__);
                    return ['code'=>404,'msg'=>'支付异常'];
                }
                break;
        }
    }

}
